//
// Created by xy on 2024/10/19.
//

#include "log.h"

// 全局日志对象定义
LogManager* g_log;

// 获取当前时间的简单实现
char* get_current_time() {
  static char buffer[20];
  struct timeval tv;
  gettimeofday(&tv, NULL);
  struct tm* tm_info = localtime(&tv.tv_sec);
  strftime(buffer, 20, "%Y-%m-%d %H:%M:%S", tm_info);
  return buffer;
}

int logLevel() {
  char* level = parseINI("level", NULL);
  int ret_level = INFO; // 默认值
  if (strcmp(level, "DEBUG") == 0) {
    ret_level = DEBUG;
  } else if (strcmp(level, "WARN") == 0) {
    ret_level = WARN;
  } else if (strcmp(level, "ERROR") == 0) {
    ret_level = ERROR;
  }
  free(level); // 统一释放
  return ret_level;
}


LogBase* initLogBase(char* path, LOGLEVEL level) {
  LogBase* log = (LogBase*)malloc(sizeof(LogBase));
  if (log == NULL) {
    ERROR_LOG("initLogBase malloc failed");
    return NULL;
  }

  FILE* file = fopen(path, "a");
  if (file == NULL){
    ERROR_LOG("initLogBase fopen failed");
    return NULL;
  }

  log->path = path;
  log->file = file;
  log->level = level;
  log->create_time = time(NULL);
  return log;
}



// 初始化日志
bool initLog() {
  g_log = (LogManager*)malloc(sizeof(LogManager));
  if (g_log == NULL) {
    ERROR_LOG("initLog malloc failed");
    return false;
  }
  g_log->main_level = logLevel();

  g_log->log[INFO - 1] = initLogBase("log/info.txt", INFO);
  g_log->log[DEBUG - 1] = initLogBase("log/debug.txt", DEBUG);
  g_log->log[WARN - 1] = initLogBase("log/warn.txt", WARN);
  g_log->log[ERROR - 1] = initLogBase("log/error.txt", ERROR);

  return true;
}

// 写入日志
bool writeLog(const char* data, LOGLEVEL log_level) {
  if (log_level < g_log->main_level) {
    return false;
  }

  printf("%s\n",data);

  // 加入到队列中

  LogBase* log = g_log->log[log_level - 1];
  if (log && log->file) {
    fprintf(log->file, "%s\n", data);
    fflush(log->file);
  }

  return true;
}

void closeLog() {
  if (g_log) {
    for (int i = 0; i < LOG_NUM; ++i) {
      LogBase* log = g_log->log[i];
      if (log) {
        if (log->file) {
          fclose(log->file);
          log->file = NULL;
        }
        free(log);
      }
    }
    free(g_log);
    g_log = NULL;
  }
}
